package a02_链表;

/**
 * <p>
 * a03_设计链表复习6
 * </p>
 *
 * @author flyduck
 * @since 2025/4/9
 */
public class a03_设计链表复习6 {

    private ListNode dummyNode;
    private int size;

    public a03_设计链表复习6() {
        this.dummyNode = new ListNode(0);
        this.size = 0;
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }

        ListNode currentNode = dummyNode.next;
        while (index > 0){//如果index = 1，那么需要进去一次
            currentNode = currentNode.next;
            index--;
        }
        return currentNode.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }


    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size){
            return;
        }

        //找到前一个
        ListNode currentNode = dummyNode;
        while (index > 0){//比如index=1，进去一次
            currentNode = currentNode.next;
            index--;
        }

        ListNode newNode = new ListNode(val);
        newNode.next = currentNode.next;
        currentNode.next = newNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }

        //找到前一个
        ListNode currentNode = dummyNode;
        while (index > 0){//比如index=1，进去一次
            currentNode = currentNode.next;
            index--;
        }

        currentNode.next = currentNode.next.next;
        size--;
    }
}
